﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace work_log {
    public class GZipClass {
        /// <summary>
        /// 转换为64位字符串输出
        /// </summary>
        /// <param name="str">需要压缩并转换的字符串</param>
        /// <returns></returns>
        public static string Base64Compress(string str) {
            byte[] tempData = Encoding.Default.GetBytes(str);
            byte[] temp2 = Compress(tempData);
            string temp3 = Convert.ToBase64String(temp2);
            return temp3;
        }

        /// <summary>
        /// 转换为字符串并输出
        /// </summary>
        /// <param name="str">需要转换并解压的字符串</param>
        /// <returns></returns>
        public static string Base64Decompress(string str) {
            byte[] tempData = Convert.FromBase64String(str);
            byte[] temp1 = Decompress(tempData);
            string temp2 = Encoding.Default.GetString(temp1);
            return temp2;
        }

        /// <summary>
        /// 压缩字节流
        /// </summary>
        /// <param name="bytes">字节</param>
        /// <returns></returns>
        private static byte[] Compress(byte[] bytes) {
            using (MemoryStream ms = new MemoryStream()) {
                GZipStream gZip = new GZipStream(ms, CompressionMode.Compress);
                gZip.Write(bytes, 0, bytes.Length);
                gZip.Close();
                return ms.ToArray();
            }
        }

        /// <summary>
        /// 解压
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        private static byte[] Decompress(byte[] bytes) {
            MemoryStream ms = new MemoryStream(bytes);
            GZipStream gZip = new GZipStream(ms, CompressionMode.Decompress);
            MemoryStream outBuffer = new MemoryStream();
            byte[] block = new byte[1024];
            while (true) {
                int bytesRead = gZip.Read(block, 0, block.Length);
                if (bytesRead <= 0)
                    break;
                else
                    outBuffer.Write(block, 0, bytesRead);
            }
            gZip.Close();
            return outBuffer.ToArray();
        }
    }
}
